import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import download from '@/utils/download';
import moment from 'moment';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Button,
  Input,
  Spin,
  Table,
  message,
  InputNumber,
  Modal,
  Select,
  Drawer,
  DatePicker,
  Upload,
} from 'antd';
import styles from './index.less';
import pen from '@/assets/knowledge/pen.png';
import deleteZdy from '@/assets/knowledge/delete.png';
import copy from 'copy-to-clipboard';
import axios from 'axios';
const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;
const { MonthPicker, RangePicker } = DatePicker;
const monthFormat = 'YYYY/MM';

class BusinessDocuments extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectPd: 'all',
      limit: 10,
      page: 1,
      totala: 2,
      query: '',
      visible4: false,
      login: false,
      fileList: [],
      url: '',
      allList: [
        { updateTime: '1564458842395', question: '<p>897789977</p>', count: '1' },
        { updateTime: '1564029969607', question: '<p>测试</p>', count: '2' },
      ],
    };
  }

  componentDidMount() {
    this.businessDocuments();
  }

  businessDocuments = () => {
    this.setState({ login: true });
    const { dispatch, currentUser } = this.props;
    const { page, limit, query } = this.state;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'businessDocuments/cloudResIndex',
        payload: { page, limit, query },
        callback: res => {

          this.setState({
            allList: res.data,
            totala: Number(res.total),
            login: false,
          });
        },
      });
    });
  };

  // 表单数据
  userInfo = () => {
    return this.props.form.getFieldsValue();
    // 使用方法
    // let user  = this.userInfo()
    //
  };

  pageWay = a => {

    this.setState({ page: a }, () => {
      this.businessDocuments();
    });
  };

  view = () => {
    let user = this.userInfo();

    this.setState({ query: user.input, page: 1 }, () => {
      this.businessDocuments();
    });
  };

  onShowSizepageWay = (a, b) => {

    this.setState({ page: a, limit: b }, () => {
      this.businessDocuments();
    });
  };

  handleDelete = item => {
    // 编辑页 downloads

    this.setState({ url: item.url });
    const { dispatch, currentUser } = this.props;
    // dispatch({
    //   type: 'businessDocuments/businesxz',
    //   url:'/file/5d440cdd5dd75a0c1c530415',
    //   payload: {},
    //   callback: (res) => {
    //
    //     let filename = decodeURIComponent(res.requestRes.headers.get('Content-Disposition').split('=')[1]);
    //     download.byBlob(res.fileBlob, filename)
    //   }
    // });
  };

  delDelete = item => {

    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'businessDocuments/removeFile',
        payload: { id: item._id },
        callback: res => {

          if (!res.code) {
            message.error('删除成功');
            this.businessDocuments();
          }
        },
      });
    });
  };

  zdysson = () => {
    this.setState({
      visible4: true,
    });
  };

  handleCancelD = e => {

    this.setState({
      visible4: false,
      fileList: [],
    });
  };

  handleCancel = () => {
    this.setState({ visible4: false, uploading: false, fileList: [], percentC: 0 });
  };

  businessWayA = () => {
    const { fileList } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {

      formData.append('file', file.originFileObj);
      // formData.append('resType', 'webUpload');
    });
    this.setState({
      uploading: true,
    });
    this.uploadFile(formData);
  };

  handleUpFile = info => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);


    fileList = fileList.map(file => {

      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    let str = fileList[0].name;
    //
    let index = str.lastIndexOf('\.');
    str = str.substring(index + 1, str.length);

    if(str==='doc'||str==='docx'||str==='xls'||str==='xlsx'||str==='ppt'||str==='pptx'||str==='ISO'||str==='RAR'||str==='zip'||str==='ACE'||str==='pdf'||str==='rm'||str==='avi'||str==='mp4'||str==='MP3'||str==='ASX'||str==='DV'||str==='VIV'||str==='txt'||str==='AFM'||str==='SCR'||str==='PBM'||str==='PSP'||str==='LOG'||str==='JTF'||str==='GL'||str==='CV'||str==='ASF'||str==='bmp'||str==='jpg'||str==='png'||str==='tif'||str==='gif'||str==='pcx'||str==='tga'||str==='exif'||str==='fpx'||str==='svg'||str==='psd'||str==='cdr'||str==='pcd'||str==='dxf'||str==='ufo'||str==='eps'||str==='ai'||str==='raw'||str==='WMF'||str==='webp'||str==='flv'||str==='mvb'||str==='wma'||str==='rmvb'||str==='DOC'||str==='DOCX'||str==='XLS'||str==='XLSX'||str==='PPT'||str==='PPTX'||str==='ios'||str==='rar'||str==='ZIP'||str==='ace'||str==='PDF'||str==='RM'||str==='ACI'||str==='MP4'||str==='mp3'||str==='asx'||str==='dv'||str==='viv'||str==='TXT'||str==='afm'||str==='scr'||str==='pbm'||str==='psp'||str==='log'||str==='gtf'||str==='gl'||str==='cv'||str==='asf'||str==='BMP'||str==='JPG'||str==='PNG'||str==='TIF'||str==='GIF'||str==='PCX'||str==='TGA'||str==='EXIF'||str==='FPX'||str==='SVG'||str==='PSD'||str==='CRD'||str==='PCD'||str==='DXF'||str==='UFO'||str==='EPS'||str==='AI'||str==='RAW'||str==='wmf'||str==='WEBP'||str==='FLV'||str==='MVB'||str==='WVA'||str==='RMVB'||str==='wps'||str==='WPS'||str==='ceb'||str==='CEB'){
      if (fileList[0].size / 1024 / 1024 > 50) {
        // 2000000
        message.error('上传限制：小于50M');
        this.setState({ fileList: [], percentC: 0 });
      } else {
        this.setState({ fileList, percentC: 0 });
      }
    }else{
      message.error('抱歉，文件格式不允许')
      this.setState({ fileList: [], percentC: 0 });
    }

  };

  uploadFile = data => {

    const token =
      JSON.parse(window.localStorage.getItem('currentUser')) == undefined
        ? ''
        : JSON.parse(window.localStorage.getItem('currentUser')).token;
    axios
      .post('/res/upload?resType=webUpload', data, {
        method: 'post',
        processData: false,
        headers: { 'Content-Type': 'application/json', token: token },
      })
      .then(res => {
        this.setState(
          {
            uploading: false,
          },
          () => {

            if (res.data.code) {
              return message.error(res.data.msg);
            } else {
              this.setState(
                {
                  visible: false,
                  visible4: false,
                  fileList: [],
                },
                () => {
                  setTimeout(() => {
                    this.setState(
                      {
                        fileList: [],
                      },
                      () => {
                        this.businessDocuments();
                      }
                    );
                  }, 1000);
                  if (res.data.msg) {
                    message.success(res.data.msg);
                  } else {
                    message.success('导入成功');
                  }
                }
              );
            }
          }
        );
      })
      .catch(error => {
        message.error('导入失败请稍等再试');
        this.setState({ uploading: false });
      });
  };

  handlefz = item => {

    copy(item.url);
    message.success('复制成功');
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { selectedRowKeys } = this.state;
    const { uploading, fileList } = this.state;
    const props = {
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      // accept: '.xlsx',
      fileList,
      onChange: this.handleUpFile,
    };
    const columns = [
      {
        title: '文档名称',
        dataIndex: 'name',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{item}</span>
            </div>
          );
        },
      },

      {
        title: '文档路径',
        dataIndex: '',
        width: 'calc(20vw)',
        render: (text, item) => {
          return (
            <div className={styles.hull}>
              {' '}
              <span style={{ marginRight: 10 }}>{item.url}</span>
            </div>
          );
        },
      },
      {
        title: '',
        dataIndex: '',
        width: 'calc(10vw)',
        render: (text, item) => {
          return (
            <div className={styles.hull}>
              <Button
                onClick={text => {
                  this.handlefz(item);
                }}
                size="small"
              >
                复制
              </Button>
            </div>
          );
        },
      },

      {
        title: '上传时间',
        dataIndex: 'createTime',
        render(item) {
          return (
            <div className={styles.hull}>
              <span>{moment(item).format('YYYY-MM')}</span>
            </div>
          );
        },
      },

      {
        title: '操作',
        render: (text, item) => {
          return (
            <div className={styles.pb}>
              <a href={this.state.url} download>
                <div
                  className={styles.buttongl}
                  onClick={text => {
                    this.handleDelete(item);
                  }}
                >
                  <img src={pen} style={{ marginRight: 5 }} />
                  下载
                </div>
              </a>
              <div
                style={{ marginLeft: 10, background: '#e8313b' }}
                className={styles.buttongl}
                onClick={text => {
                  this.delDelete(item);
                }}
              >
                <img src={deleteZdy} style={{ marginRight: 5 }} />
                <span>删除</span>
              </div>
            </div>
          );
        },
      },
    ];
    return (
      <Suspense fallback={<PageLoading />}>
        <PageHeaderWrapper>
          <div style={{ minHeight: 'calc(100vh - 150px)', background: '#ffffff' }}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10, color: '#4B5475', fontWeight: 600 }} xs={24}>
                <div className={styles.title}>
                  <span>业务文档</span>
                </div>
              </Col>
            </Row>

            <div className="cardZdy">
              <Card className="tableyc" bordered={false}>
                <Form layout="inline">
                  <FormItem>
                    <Button onClick={this.zdysson} icon="upload" type="primary">
                      文件上传
                    </Button>
                  </FormItem>
                  <span style={{ float: 'right' }}>
                    <FormItem>
                      <div>
                        {getFieldDecorator('input', {
                          initialValue: '',
                        })(<Input onPressEnter={this.view} placeholder="请输入文档名称" />)}
                      </div>
                    </FormItem>
                    <FormItem>
                      <Button onClick={this.view} icon="check">
                        查看
                      </Button>
                    </FormItem>
                  </span>
                </Form>
                <Spin spinning={this.state.login}>
                  <Table
                    className="zdyTable"
                    onChange={this.pXhandleChange}
                    style={{ padding: '20px 0px 0px 0px' }}
                    columns={columns}
                    dataSource={this.state.allList} // 数据
                    // onChange={this.handleChange}
                    pagination={{
                      // 分页
                      total: this.state.totala,
                      pageSize: this.state.limit, // 显示几条一页
                      current: this.state.page, // 当前页
                      showSizeChanger: true, // 是否显示可以设置几条一页的选项
                      showQuickJumper: true,
                      onChange: this.pageWay,
                      onShowSizeChange: this.onShowSizepageWay,
                    }}
                  />
                </Spin>
              </Card>
              <Modal
                className="modelZdy"
                title="导入业务文档"
                okText="开始上传"
                cancelText="取消"
                visible={this.state.visible4}
                onCancel={this.handleCancelD}
                footer={[
                  <Button key="back" onClick={this.handleCancel}>
                    取消
                  </Button>,
                  <Button
                    key="submit"
                    type="primary"
                    loading={uploading}
                    disabled={fileList.length === 0}
                    onClick={this.businessWayA}
                  >
                    {uploading ? '导入中' : '开始导入'}
                  </Button>,
                ]}
                // onOk={this.handleOkD}
                // onCancel={this.handleCancelD}
              >
                <Row>
                  <Col span={24}>
                    {/* <div style={{ height: 10 }}></div> */}
                    <div style={{ float: 'left', marginRight: 10 }}>选择要导入的文件</div>
                    {/* <div onClick={this.dictTemp} style={{ color: '#26cbff', cursor: 'pointer', float: 'right' }}>下载导入模版</div> */}
                    <div>
                      <Upload
                        {...props}
                        fileList={this.state.fileList}
                        accept=".DOC,doc,.docx,.DOCX,.xls,.XLS,.xlsx,.XLSX,.ppt,.PPT,.pptx,.PPTX,.ISO,.ios,.RAR,.rar,.zip,.ZIP,.ACE,.pdf,.rm,.RM,.avi,.mp4,.MP4,.mp3,.MP3,.ASX,.DV,.VIV,.txt,.TCX,.AFM,.afm,.SCR,.scr,.PBM,.pbm,.PSP,.psp,.LOG,.JTF,.GL,.CV,.ASF,.bmp,.jpg,.JPG,.png,.PNG,.tif,.TIF,.gif,.GIF,.pcx,.PCX,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw,.WMF,.webp,.flv,.wma,.mvb,.rmvb,.wps,.ceb,WPS,.CEB"
                      >
                        <Button className={styles.float}>
                          <Icon type="upload" /> 选择文件
                        </Button>
                      </Upload>
                    </div>
                    <div style={{ height: 20 }} />
                  </Col>
                </Row>
              </Modal>
            </div>
          </div>
        </PageHeaderWrapper>
      </Suspense>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(BusinessDocuments));
